package com.neusoft.controller;

import java.math.BigDecimal;
import java.util.List;

import com.neusoft.po.CommonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import com.neusoft.po.OrderDetailet;
import com.neusoft.po.Orders;
import com.neusoft.service.OrdersService;

@RestController
@RequestMapping("/OrdersController")
@RefreshScope
public class OrdersController {
    @Autowired
    private OrdersService ordersService;
    
	@PostMapping("/createOrders/{userId}/{businessId}/{orderTotal}/{daId}/{orderState}/{orderItems}")
	public CommonResult<List> createOrders(@RequestParam("userId") String userId,
												@RequestParam("businessId") Integer businessId,
												@RequestParam("orderTotal") Double orderTotal,
												@RequestParam("daId") Integer daId,
												@RequestParam("orderState") Integer orderState,
												@RequestParam("orderItems") String orderItemsJson) {
		try {
			// 将 orderItems 从 JSON 字符串转换为对象列表
			ObjectMapper objectMapper = new ObjectMapper();
			List<OrderDetailet> orderItems = objectMapper.readValue(orderItemsJson, new TypeReference<List<OrderDetailet>>() {
			});

			Orders order = new Orders();
			order.setUserId(userId);
			order.setBusinessId(businessId);
			order.setOrderTotal(orderTotal);
			order.setDaId(daId);
			order.setOrderState(orderState);

			int orderId = ordersService.createOrders(order, orderItems);
			ResponseEntity<Integer> i=ResponseEntity.ok(orderId);
			return new CommonResult(200, "success", i);
		} catch (Exception e) {
			ResponseEntity<Integer> i=ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
			return new CommonResult(200, "success", i);
		}
	}

	@GetMapping("/getOrdersById/{orderId}")
	public CommonResult<List> getOrdersById(@RequestParam("orderId") Integer orderId) throws Exception {
		Orders i = ordersService.getOrdersById(orderId);
		// 输出订单信息到日志
		System.out.println("订单信息: " + order);
		return new CommonResult(200, "success", i);
	}

	@GetMapping("/listOrdersByUserId/{userId}")
	public CommonResult<List> listOrdersByUserId(Orders orders) throws Exception {
		List<Orders> i=ordersService.listOrdersByUserId(orders.getUserId());
		return new CommonResult(200, "success", i);
	}

	/**
	 * 更新订单状态并处理积分
	 *
	 * @param payload 包含 orderId、orderState 和 usedScore
	 * @return 响应实体
	 */
	@PostMapping("/updateOrderState/{orderId}")
	public CommonResult<List> updateOrderState(@RequestBody Map<String, Object> payload) {
		// 解析 payload 并转换为相应的类型
		Long orderId = null;
		Integer orderState = null;
		Integer usedScore = null;

		try {
			orderId = Long.valueOf(payload.get("orderId").toString());
			orderState = Integer.valueOf(payload.get("orderState").toString());
			// 如果 payload 中包含 usedScore
			if (payload.containsKey("usedScore")) {
				usedScore = Integer.valueOf(payload.get("usedScore").toString());
			} else {
				usedScore = 0; // 如果没有传递积分使用值，则默认为 0
			}
		} catch (Exception e) {
			ResponseEntity<?> i=ResponseEntity.badRequest().body("Invalid parameters: " + e.getMessage());
			return new CommonResult(200, "success", i);
		}

		// 确保所有参数都不为空
		if (orderId == null || orderState == null) {
			return ResponseEntity.badRequest().body("Missing required parameters");
		}

		// 更新订单状态并处理积分
		boolean isUpdated = ordersService.updateOrderState(orderId, orderState, usedScore);

		if (isUpdated) {
			return ResponseEntity.ok(Map.of("success", true));
		} else {
			return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Update failed");
		}
	}

}